package cn.tedu.oa_system.repository.impl;

import cn.tedu.oa_system.pojo.vo.UserSimpleVO;
import cn.tedu.oa_system.repository.IUserRedisRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @Author MW
 * @Description 用户缓存仓库接口实现类
 * @CreateDate 2023/1/7
 */
@Repository
public class UserRedisRepository implements IUserRedisRepository {

    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;

    @Override
    public Boolean exists(Long id) {
        String key=KEY_USER_ITEM_PREFIX+id;
        return redisTemplate.hasKey(key);
    }

    @Override
    public void saveEmptyValue(Long id) {
        String key=KEY_USER_ITEM_PREFIX+id;
        redisTemplate.opsForValue().set(key,null,30, TimeUnit.SECONDS);
    }

    @Override
    public void save(UserSimpleVO userSimpleVO) {
        String key=KEY_USER_ITEM_PREFIX+userSimpleVO.getUserId();
        redisTemplate.opsForValue().set(key,userSimpleVO);
    }

    @Override
    public void save(List<UserSimpleVO> users) {
        for (UserSimpleVO userSimpleVO : users) {
            redisTemplate.opsForList().rightPush(KEY_USER_LIST,userSimpleVO);
        }
    }

    @Override
    public Boolean deleteList() {
        return redisTemplate.delete(KEY_USER_LIST);
    }

    @Override
    public void deleteAllItem() {
        Set<String> keys = redisTemplate.keys(KEY_USER_ITEM_PREFIX + "*");
        redisTemplate.delete(keys);
    }

    @Override
    public UserSimpleVO getUserSimpleById(Long id) {
        String key=KEY_USER_ITEM_PREFIX+id;
        UserSimpleVO userSimpleVO=(UserSimpleVO) redisTemplate.opsForValue().get(key);
        if (userSimpleVO == null) {
            return null;
        }else {
            return userSimpleVO;
        }
    }
}
